#!/usr/bin/env bash

FILE_PATH="$1"
PV_WIDTH="$2"
PV_HEIGHT="$3"
HORIZONTAL_POS="$4"
VERTICAL_POS="$5"

HIGHLIGHT_THEME="$HOME/.config/my_colors.highlight_theme"

preview() {
    case "$TERM" in
        xterm-kitty)
            kitty +icat --transfer-mode memory --stdin no \
                --place "${PV_WIDTH}x${PV_HEIGHT}@${HORIZONTAL_POS}x${VERTICAL_POS}" \
                "$1" < /dev/null > /dev/tty
            ;;

        *-256color)
            /usr/bin/chafa -s "${PV_WIDTH}x${PV_HEIGHT}" -f symbols --symbols ascii \
                --polite on "$1" 2> /dev/null
            ;;

        *)
            /usr/bin/chafa -s "${PV_WIDTH}x${PV_HEIGHT}" --animate off \
                --polite on "$1" 2> /dev/null
            ;;
    esac
}

vidthumb() {
    thumbnail="$HOME/.cache/thumbnails/$(sha256sum "$1" | awk "{ print \$1 }").png"
    if [ -f "$thumbnail" ]; then
        echo "$thumbnail"
        return
    else
        mkdir -p "$HOME/.cache/thumbnails"
        ffmpegthumbnailer -i "$1" -o "$thumbnail" -s 0 2>/dev/null
    fi
    echo "$thumbnail"
}

case "$(file --dereference --brief --mime-type -- "$FILE_PATH")" in
    video/* | audio/*)
        preview "$(vidthumb "$FILE_PATH")"
        exit 1
        ;;
    image/*)
        preview "$FILE_PATH"
        exit 1
        ;;
    text/* | */xml | application/json | application/javascript)
        highlight -WO xterm256 -t 8 -s "$HIGHLIGHT_THEME" -- "$FILE_PATH"
        exit 1
        ;;
    application/x-bzip* | application/gzip | application/x-tar)
        tar -tf "$FILE_PATH" | tree --fromfile .
        exit 1
        ;;
    application/zip)
        unzip -l "$FILE_PATH"
        exit 1
        ;;
esac
file --brief -- "$FILE_PATH"
echo
hexdump -C -- "$FILE_PATH"

